package com.ypx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ypx.bean.User;
import com.ypx.common.R;
import com.ypx.exception.CustomException;
import com.ypx.service.UserService;
import com.ypx.utils.SMSUtils;
import com.ypx.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Tang
 * @date 2023/2/24
 */
@Slf4j
@RequestMapping("/user")
@Api(tags = "用户登录管理")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取验证码 --》发送短信
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //1.获取前端传递手机号
        String phone = user.getPhone();

        //2.生成验证码（调用util工具类）
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        log.info("code = {}", code);

        //3.发送验证码到指定的手机号
        SMSUtils.sendMessage("易鹏祥的个人博客", "SMS_460860336", phone, code.toString());

        //4.保存验证码,用HttpSession
//        session.setAttribute(phone, code);
        //用redis缓存
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

        //5.返回结果
        return R.success(code.toString());
    }

    /**
     * 用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String, Object> map, HttpSession session){
        //1.获取前端传递过来的手机号和验证码
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");

        //2.校验验证码是否正确，如果不一致就返回错误信息
//        Object validateCode =  session.getAttribute(phone);

        //优化：从redis中获取
        Object validateCode = redisTemplate.opsForValue().get(phone);

        if (validateCode == null) {
            throw new CustomException("验证码已失效！");
        }
        if (!validateCode.toString().equals(code)) {
            throw new CustomException("验证码错误！");
        }

        //3.根据手机号查询用户表，如果不存在该用户，需要初始化数据
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User user = userService.getOne(wrapper); // null
        if (user == null) {
            user = new User();
            user.setName("u_"+phone);
            user.setPhone(phone);
            //4.保存新的用户（第一次登录需要做的）
            userService.save(user);
        }
        //5.登录成功需要保存userId到session中，返回结果
        session.setAttribute("userId", user.getId());

        //登录成功，就把验证码从redis中删除
        redisTemplate.delete(phone);
        return R.success("登录成功！");

    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest request){
        request.getSession().removeAttribute("userId");
        return R.success("退出成功！");
    }
}
